<script lang="ts" setup>
import { ref, computed, Ref } from "vue";
import { Edit } from "@element-plus/icons-vue";
import Admin from "@/types/response/admin";
import { ElMessage } from "element-plus";
import {
  getAllAdmin,
  addAdmin,
  updateAdmin
} from "@/axios/admin/adminReq";
import { changeUserState, getUserStatesByIds } from "@/axios/admin/accountReq";

// 扩展 Admin 接口以包含 state 属性
interface ExtendedAdmin extends Admin {
  state?: number;
}

const gender = [
  {
    value: 1,
    label: "男",
  },
  {
    value: 0,
    label: "女",
  },
];

const stateOptions = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "停用",
  },
];
//用户搜索时输入的名字
const name = ref("");

//用户搜索时输入的状态
const state = ref<number>(1);

const rulesFormRef = ref();

// 添加管理员数据模型
const admins: Ref<Admin[]> = ref([]);

const adminModel = ref<ExtendedAdmin>({
  adminId: null,
  name: "",
  gender: 1,
  birthDate: "",
  idNumber: "",
  phone: "",
  createdTime: "",
  state: 1,
});
// 控制添加管理员弹窗
const dialogVisible = ref(false);

// 性别选择框绑定的值
const genderValue = ref<number>();

// 状态选择框绑定的值
const stateValue = ref<number>();

// 获取管理员列表
const getAdmins = async () => {
  let result = await getAllAdmin();
  admins.value = result;

  let states = await getUserStatesByIds(
    admins.value.map((admin) => admin.adminId)
  );

  admins.value = admins.value.map((admin) => ({
    ...admin,
    state: states.get(admin.adminId) ?? 1,
  }));
};
getAdmins();

// 添加管理员表单校验
const rules = {
  adminId: [{ required: true, message: "请输入管理员ID", trigger: "blur" }],
  name: [{ required: true, message: "请输入管理员姓名", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  birthDate: [{ required: true, message: "请输入出生年月", trigger: "blur" }],
  idNumber: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
};

//添加管理员函数
const addAdminn = () => {
  title.value = "新增管理员";
  dialogVisible.value = true;
  genderValue.value = 1;
  editIndex.value = null;
  rulesFormRef.value?.resetFields();
};
const editIndex = ref<number | null>(null);

const editAdmin = (index: number, admin: ExtendedAdmin) => {
  title.value = "编辑管理员";
  dialogVisible.value = true;
  adminModel.value = { ...admin };
  genderValue.value = admin.gender;
  editIndex.value = index;
  rulesFormRef.value?.clearValidate();
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (genderValue.value !== undefined) {
    adminModel.value.gender = genderValue.value;
  }
  if (stateValue.value) {
    adminModel.value.state = stateValue.value;
  }

  try {
    if (editIndex.value !== null) {
      // 更新管理员信息
      const success = await updateAdmin(adminModel.value);
      if (success) {
        admins.value[editIndex.value] = { ...adminModel.value };
        editIndex.value = null;
        ElMessage({
          type: "success",
          message: "更新信息成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: "更新信息失败",
        });
      }
    } else {
      // 添加管理员信息
      const newAdmin = await addAdmin(adminModel.value); // 调用 addAdmin 函数
      const states = await getUserStatesByIds([newAdmin.adminId]); // 将 adminId 放入数组中传递
      const status = states.get(newAdmin.adminId); // 获取新管理员的状态
      // 使用类型断言
      const newAdminWithState = {
        ...newAdmin,
        state: status || 1, // 使用数字类型的默认值
      } as Admin;

      admins.value.push(newAdminWithState);
      genderValue.value = 1;
      stateValue.value = 1;
    }

    console.log("提交的管理员信息:", adminModel.value);
  } catch (error) {
    ElMessage({
      type: "error",
      message: "提交失败",
    });
  } finally {
    dialogVisible.value = false;
  }
};

// 切换管理员状态的方法
const toggleState = async (admin: any) => {
  try {
    const newState = admin.state === 1 ? 0 : 1;
    const success = await changeUserState(admin.adminId, newState);
    if (success) {
      admin.state = newState;
      ElMessage({
        type: "success",
        message: "状态切换成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "状态切换失败",
      });
    }
  } catch (error) {
    console.error("切换状态时出错:", error);
  }
};

const title = ref("");

const filteredAdmins = computed(() => {
  const result = admins.value.filter(
    (admin: ExtendedAdmin) =>
      (!name.value || admin.name.includes(name.value)) &&
      (state.value === undefined || admin.state === state.value)
  );
  return result;
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>管理员管理</span>
        <div class="extra">
          <el-button type="primary" @click="addAdminn">新增管理员</el-button>
        </div>
      </div>
    </template>
    <!-- 搜素表单 -->
    <el-form inline>
      <el-form-item label="姓名：">
        <el-input
          v-model="name"
          style="width: 240px"
          clearable
          placeholder="请输入筛选姓名"
        />
      </el-form-item>
      <el-form-item label="状态：">
        <el-select
          v-model="state"
          style="width: 240px"
          clearable
          placeholder="请选择筛选状态"
        >
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table :data="filteredAdmins" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="性别" prop="gender">
        <template #default="scope">
          {{
            gender.find((g) => g.value === scope.row.gender)?.label || "未知"
          }}
        </template>
      </el-table-column>
      <el-table-column label="电话号码" prop="phone"></el-table-column>
      <el-table-column label="状态" prop="state">
        <template #default="scope">
          {{
            stateOptions.find((s) => s.value === scope.row.state)?.label ||
            "未知"
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            :disabled="scope.row.state === 0"
            @click="editAdmin(scope.$index, scope.row)"
          ></el-button>
          <el-button
            :type="scope.row.state === 1 ? 'danger' : 'success'"
            circle
            plain
            @click="toggleState(scope.row)"
          >
            {{
              stateOptions.find((s) => s.value === scope.row.state)?.label ===
              "启用"
                ? "停用"
                : "启用"
            }}
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="adminModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="管理员姓名" prop="name">
          <el-input
            v-model="adminModel.name"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="genderValue" placeholder="请选择性别">
            <el-option
              v-for="item in gender"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthDate">
          <el-date-picker
            v-model="adminModel.birthDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input
            v-model="adminModel.idNumber"
            minlength="18"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input
            v-model="adminModel.phone"
            :disabled="editIndex !== null"
            minlength="11"
            maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
